


from . import models
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from rest_framework_jwt.serializers import jwt_encode_handler, jwt_payload_handler
class UserSerializer(serializers.ModelSerializer):
    username = serializers.CharField()
    class Meta:
        model = models.User
        fields = ['username','password','id']
        extra_kwargs = {
            'id':{'read_only':True},
            'password':{'write_only':True}
        }

    def validate(self, attrs):
        user = self._get_user(attrs)


        token = self._get_token(user)
        print(token)
        self.context['token'] = token
        self.context['username'] = user.username
        return attrs


    def _get_user(self,attrs):
        username = attrs.get('username')
        password = attrs.get('password')


        import re

        if re.match(r'^1[3-9][0-9]{9}$',username):
            user = models.User.objects.filter(mobile=username).first()
        elif re.match(r'^.+@.+$',username):
            user = models.User.objects.filter(email=username).first()
        else:
            user = models.User.objects.filter(username=username).first()
        if user:
            res=user.check_password(password)
            if res:
                return user
            else:
                raise ValidationError({'password':'密码不正确'})
        else:
            raise ValidationError({'username': '用户名不存在'})

    def _get_token(self,user):


        payload = jwt_payload_handler(user)

        token = jwt_encode_handler(payload)

        return token



